package org.testmyapp.tasks;

import java.util.List;
import java.util.Map;

import org.apache.ecs.html.Var;
import org.testmyapp.engine.IEngineServices;
import org.testmyapp.entities.RefundPart;
import org.testmyapp.global.Variable;
import org.testmyapp.persistence.BusinessObjectPersistenceProvider;
import org.testmyapp.servicetasks.RefundAuthorisation;

public class CheckManualAdaption implements TaskWorker {

	public String validate(IEngineServices aes, Map<String, String[]> parameterMap, String processInstanceId,
			BusinessObjectPersistenceProvider bopp) {
		
		String istOk = parameterMap.get("correctionManOk")[0];
		
		if (istOk == null) throw new RuntimeException("Techn. Fehler, keine Entscheidung ob Erstattungskorrektur ok");
		
		if (istOk.equals("false")) {
			Integer oldRefund = (Integer) aes.getVariable(Variable.OLDREFUND.getName(), processInstanceId);
			RefundPart rpForCorrect = (RefundPart) aes.getVariable(Variable.REFUNDPARTTOCORRECT.getName(), processInstanceId);
			rpForCorrect.setRefundSum(oldRefund);
			
			@SuppressWarnings("unchecked")
			List<RefundPart> refundPartList = (List<RefundPart>) aes.getVariable(Variable.REFUNDPARTLIST.getName(), processInstanceId);

			RefundPart toReplace = null;
			for (RefundPart rp : refundPartList) {
				if (rp.getRefundPartNr() == rpForCorrect.getRefundPartNr()
						&& rp.getBillPosition().getBillPositionNr().equals(rpForCorrect.getBillPosition().getBillPositionNr())
						&& rp.getBillPosition().getBill().getBillNr().equals(rpForCorrect.getBillPosition().getBill().getBillNr())) {
					toReplace = rp;
				}
			}

			if (toReplace == null) {
				throw new RuntimeException("Technischer Fehler: Kein RP da :(");
			}

			refundPartList.remove(toReplace);
			refundPartList.add(rpForCorrect);
		}
		
		return "";
	}

}
